# _*_ coding:utf-8 _*_
from Tkinter import *
import qrcode
import sys
import urllib
import urllib2
import json
import sys
import io
reload(sys)
sys.setdefaultencoding('utf8')


class Constant:
    APP_HOST = "https://mobile.appchina.com/market/api"
    param = '{"apiVer":23,"guid":"06b15137-908f-4f51-b035-e296d5fda1b6","imei":"869394021134371","type":"app.list.search","query":"%s","size":20,"indexStart":0,"filter":{"markets":["market","spider"]},"transable":true,"clientTime":1517566460270,"imglevel":3,"gpuType":4,"clientVersionCode":30061345,"channel":"ac.ex.360"}'
    deviceId = "869394021134371"
    referer = "06b15137-908f-4f51-b035-e296d5fda1b6"
    paramHistory = '{"apiVer":23,"guid":"06b15137-908f-4f51-b035-e296d5fda1b6","imei":"869394021134371","type":"app.pastdetails","id":%d,"packagename":"%s","start":0,"size":100,"clientTime":1517566460270,"imglevel":3,"gpuType":4,"clientVersionCode":30061345,"channel":"ac.ex.360"}'
    api = "market.MarketAPI"
    params = {}
    apkSearchList = [];
    apkHistoryList = [];
    url = ""
class Window():
    def __init__(self,root):
        self.root = root;
        root.title("Apk历史版本搜索工具")
        self.keyVar = StringVar()
        self.keyVar.set('新东方在线')
        self.version = StringVar()
        self.version.set("")
        self.topFrame = Frame(self.root, width=550, height=50, borderwidth=2)
        self.topFrame.grid(row=0, column=0)
        self.midFrame = Frame(self.root,width=550,height=20,borderwidth=2)
        self.midFrame.grid(row=1,column=0)
        self.contentFrame = Frame(self.root, width=550, height=500, borderwidth=1)
        self.contentFrame.grid(row=2, column=0)
        self.apkEntry = Entry(self.topFrame, textvariable=self.keyVar).pack(side=LEFT)
        self.apkSearchBtn = \
            Button(self.topFrame, text="搜索",
                   command=lambda: APP_REQUEST.search_apk_list(APP_REQUEST(), self)).pack(side=LEFT)
        self.textLabel = Entry(self.midFrame, width=80,bg='white',background='gray',textvariable=self.version).pack(side=TOP)

        self.apkListBox = Listbox(self.contentFrame,width=40,height=30,selectmode=BROWSE);
        self.apkListBox.bind('<Button-1>',self.click_button)
        self.apkListBox.pack(side=LEFT)

        self.apkHistoryBox = Listbox(self.contentFrame,width=50,height=30,selectmode=BROWSE)
        self.apkHistoryBox.bind('<Button-1>',self.click_history_button)
        self.apkHistoryBox.pack(side=LEFT)

    def changeText(self):
        self.version.set(Constant.url)
        # image_bytes = urllib2.urlopen(Constant.url).read()
        # data_stream = io.BytesIO(image_bytes)
        # # open as a PIL image object
        # pil_image = Image.open(data_stream)
        # w, h = pil_image.size
        # tk_image = ImageTk.PhotoImage(pil_image)
        # self.imgLabel['image'] = tk_image
    def click_button(self, event):
        self.curIndex = self.apkListBox.nearest(event.y)
        print(self.curIndex)
        self.curIndex = event.widget.nearest(event.y)
        searchBean = Constant.apkSearchList[self.curIndex]
        APP_REQUEST.search_apk_history(APP_REQUEST(),self,searchBean)
        print(searchBean)
    def click_history_button(self,event):
        self.curIndex = self.apkHistoryBox.nearest(event.y)
        print(self.curIndex)
        self.curIndex = event.widget.nearest(event.y)
        print(Constant.apkHistoryList[self.curIndex])
        Constant.url = Constant.apkHistoryList[self.curIndex]['apkUrl']
        self.changeText()
        print Constant.url
    def make_qr(str, save):
        qr = qrcode.QRCode(
            version=4,  # 生成二维码尺寸的大小 1-40 1:21*21（21+(n-1)*4）
            error_correction=qrcode.constants.ERROR_CORRECT_M,  # L:7% M:15% Q:25% H:30%
            box_size=10,  # 每个格子的像素大小
            border=2,  # 边框的格子宽度大小
        )
        qr.add_data(str)
        qr.make(fit=True)
        img = qr.make_image()
        img.save(save)


class APP_REQUEST:
    # def show_img(self,window):
    #     image_bytes = urllib2.urlopen(Constant.url).read()
    #     data_stream = io.BytesIO(image_bytes)
    #     # open as a PIL image object
    #     pil_image = Image.open(data_stream)
    #     w, h = pil_image.size
    #     tk_image = ImageTk.PhotoImage(pil_image)
    #     window.textLabel.image_create(END,image=tk_image)
    #     window.imgLabel['image'] = tk_image
    def search_apk_list(self,window):
        Constant.params['deviceId'] = Constant.deviceId
        Constant.params['referer'] = Constant.referer
        Constant.params['api'] = Constant.api
        print window.keyVar.get()
        Constant.params['param'] = (Constant.param % window.keyVar.get())
        print Constant.params
        encodeData = urllib.urlencode(Constant.params)
        try:
            request = urllib2.Request(url=Constant.APP_HOST, data=encodeData)
            page = urllib2.urlopen(request)
            data = page.read()
            print data
            data = json.loads(data)
            print data['name']+" list.size(): " + str(len(data['list']))
            window.apkListBox.delete(0,window.apkListBox.size())
            for listBean in data['list']:
                window.apkListBox.insert(END,listBean['name'])
            Constant.apkSearchList = data['list']
            page.close()
            return data['list']
        except urllib2.URLError, e:
            if hasattr(e, "code"):
                self.keyJson = e.code
            if hasattr(e, "reason"):
                self.keyJson = e.reason
        else:
            print "ERROR"

    def search_apk_history(self,window,apkSearchBean):
        Constant.params['deviceId'] = Constant.deviceId
        Constant.params['referer'] = Constant.referer
        Constant.params['api'] = Constant.api
        Constant.params['param'] = (Constant.paramHistory % (apkSearchBean['id'],apkSearchBean["packageName"]))
        print Constant.params
        encodeData = urllib.urlencode(Constant.params)
        try:
            request = urllib2.Request(url=Constant.APP_HOST, data=encodeData)
            page = urllib2.urlopen(request)
            data = page.read()
            print data
            data = json.loads(data)
            window.apkHistoryBox.delete(0,window.apkHistoryBox.size())
            for bean in data['list']:
                window.apkHistoryBox.insert(END,bean['versionName'])
                print bean['versionName']
            Constant.apkHistoryList = data['list']

            page.close()
        except urllib2.URLError, e:
            if hasattr(e, "code"):
                self.keyJson = e.code
            if hasattr(e, "reason"):
                self.keyJson = e.reason
        else:
            print "ERROR"

if __name__ == '__main__':
    root = Tk()
    app = Window(root)
    root.minsize(860,480)
    # 主消息循环:
    root.mainloop()
